package com.e2oto.seller.modules.seller.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.DrawerLayout;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

import com.e2oto.seller.R;
import com.e2oto.seller.common.base.BaseMvpActivity;
import com.e2oto.seller.common.utils.LogTools;
import com.e2oto.seller.common.utils.RxBus;
import com.e2oto.seller.common.utils.ToastUtils;
import com.e2oto.seller.modules.seller.adapter.SelectImageAdapter;
import com.e2oto.seller.modules.seller.adapter.SellerAddCategoryTagAdapter;
import com.e2oto.seller.modules.seller.adapter.SystemSecondCategoryTagAdapter;
import com.e2oto.seller.modules.seller.bean.AddGoodsFirstStepResultBean;
import com.e2oto.seller.modules.seller.bean.GoodsInfoBean;
import com.e2oto.seller.modules.seller.bean.RxBusBean;
import com.e2oto.seller.modules.seller.bean.SecondSystemCategoryBean;
import com.e2oto.seller.modules.seller.bean.SellerAddCategoryBean;
import com.e2oto.seller.modules.seller.dto.AddGoodsAllCategoryBean;
import com.e2oto.seller.modules.seller.presenter.AddGoodsBaseInfoPresenter;
import com.e2oto.seller.modules.seller.views.AddGoodsBaseInfoView;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import butterknife.BindView;
import butterknife.OnClick;
import me.iwf.photopicker.PhotoPicker;

/**
 * Created by ZhangLiQiang on 2017/11/26.
 */

public class AddGoodsBaseInfoActivity extends BaseMvpActivity<AddGoodsBaseInfoView, AddGoodsBaseInfoPresenter> implements AddGoodsBaseInfoView {

    @BindView(R.id.add_goods_base_info_gv)
    GridView imageGridView;
    @BindView(R.id.add_goods_base_info_drawer_layout)
    DrawerLayout drawerLayout;
    @BindView(R.id.add_goods_base_info_seller_added_category)
    TagFlowLayout sellerAddedFlowLayout;
    @BindView(R.id.add_goods_base_info_system_category)
    TagFlowLayout systemFlowLayout;
    @BindView(R.id.add_goods_base_info_system_category_tv)
    TextView sysCategoryTv;
    @BindView(R.id.add_goods_base_info_seller_added_category_tv)
    TextView sellerCategoryTv;
    @BindView(R.id.add_goods_base_info_name_tv)
    EditText goodsNameEt;
    @BindView(R.id.add_goods_base_info_keyword_tv)
    EditText keyWordEt;
    @BindView(R.id.add_goods_base_info_old_price_et)
    EditText oldPriceEt;


    private int isBatch = 1;//0零售 1批发 现在只做了批发 还没做零售

    private SelectImageAdapter selectImageAdapter;
    private List<SecondSystemCategoryBean> secondSystemCategoryBeanList;
    private List<SellerAddCategoryBean> sellerAddCategoryBeanList;
    private SystemSecondCategoryTagAdapter systemSecondCategoryTagAdapter;
    private SellerAddCategoryTagAdapter sellerAddCategoryTagAdapter;
    private List<Integer> selectedSysCatIds = new ArrayList<>();

    private GoodsInfoBean goodsInfoBean;//修改商品时传进来

    @Override
    protected AddGoodsBaseInfoPresenter createPresenter() {
        return new AddGoodsBaseInfoPresenter();
    }

    @Override
    protected int getContentView() {
        return R.layout.activity_add_goods_base_info;
    }

    @Override
    protected void afterView(Bundle savedInstanceState) {
        super.afterView(savedInstanceState);
        drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
        drawerLayout.addDrawerListener(new DrawerLayout.SimpleDrawerListener() {
            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
            }
        });
        selectImageAdapter = new SelectImageAdapter(this, 6);
        imageGridView.setAdapter(selectImageAdapter);

        systemSecondCategoryTagAdapter = new SystemSecondCategoryTagAdapter(new ArrayList(), this);
        systemFlowLayout.setAdapter(systemSecondCategoryTagAdapter);

        sellerAddCategoryTagAdapter = new SellerAddCategoryTagAdapter(new ArrayList(), this);
        sellerAddedFlowLayout.setAdapter(sellerAddCategoryTagAdapter);

        mPresenter.getCategory(isBatch);//暂时写死1 还能是是0

        goodsInfoBean = (GoodsInfoBean) getIntent().getSerializableExtra("data");
        if (goodsInfoBean != null) {//不为空代表修改
            goodsNameEt.setText(goodsInfoBean.getName());
            keyWordEt.setText(goodsInfoBean.getSearch_words());
            oldPriceEt.setText(goodsInfoBean.getMarket_price());
            selectImageAdapter.addStringList(goodsInfoBean.getCover());


        }
    }

    @OnClick({R.id.toolbar_left_btn, R.id.add_goods_base_info_commit, R.id.add_goods_set_category_rl,
            R.id.add_goods_set_seller_added_category_rl, R.id.add_goods_base_info_commit_category})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.toolbar_left_btn:
                finish();
                break;
            case R.id.add_goods_base_info_commit:
                String goodsName = goodsNameEt.getText().toString().trim();
                String keyword = keyWordEt.getText().toString().trim();
                String oldPrice = oldPriceEt.getText().toString().trim();
                if (TextUtils.isEmpty(goodsName)) {
                    showMessage("请输入商品名称");
                    return;
                }
                if (TextUtils.isEmpty(keyword)) {
                    showMessage("请输入商品关键字");
                    return;
                }
                if (TextUtils.isEmpty(oldPrice)) {
                    showMessage("请输入原价");
                    return;
                }

                if (goodsInfoBean == null) {
                    mPresenter.addGoodsFirstStep(selectedSysCatIds, goodsName, keyword, oldPrice, selectImageAdapter.getStringList());
                } else {
                    int goodsId = isBatch == 0 ? goodsInfoBean.getGoods_id() : goodsInfoBean.getBatch_goods_id();
                    mPresenter.updateGoodsInfo(goodsId, selectedSysCatIds, goodsName, keyword, oldPrice, selectImageAdapter.getStringList());
                }


                break;
            case R.id.add_goods_set_category_rl:
            case R.id.add_goods_set_seller_added_category_rl:
                if (sellerAddCategoryBeanList != null && secondSystemCategoryBeanList != null) {
                    drawerLayout.openDrawer(Gravity.RIGHT);
                } else {
                    showMessage("无法获取分类列表");
                }
                break;
            case R.id.add_goods_base_info_commit_category:
                selectedSysCatIds.clear();
                if (systemFlowLayout.getSelectedList().iterator().hasNext()) {
                    StringBuilder sb = new StringBuilder();

                    List<Integer> selectPositions = new ArrayList<>(systemFlowLayout.getSelectedList());
                    for (int i : selectPositions) {
                        selectedSysCatIds.add(systemSecondCategoryTagAdapter.getDataList().get(i).getId());
                        sb.append(systemSecondCategoryTagAdapter.getDataList().get(i).getName() + ",");
                    }
                    sb.deleteCharAt(sb.length() - 1);
                    sysCategoryTv.setText(sb.toString());

                } else {
                    showMessage("请选择店铺分类");
                    return;
                }
                if (sellerAddedFlowLayout.getSelectedList().iterator().hasNext()) {
                    int selectPosition = sellerAddedFlowLayout.getSelectedList().iterator().next();
                    selectedSysCatIds.add(sellerAddCategoryTagAdapter.getDataList().get(selectPosition).getId());
                    String selectSysName = sellerAddCategoryTagAdapter.getDataList().get(selectPosition).getName();
                    sellerCategoryTv.setText(selectSysName);

                } else {
                    showMessage("请选择系统分类");
                    return;
                }

                drawerLayout.closeDrawers();
                LogTools.e(selectedSysCatIds.toString());
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == PhotoPicker.REQUEST_CODE) {
            if (data != null) {
                List<String> images = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
                for (String imagePath : images) {
                    selectImageAdapter.addOneImage(imagePath);
                }
            }
        }
    }

    @Override
    public void showMessage(String msg) {
        ToastUtils.INSTANCE.showToast(this, msg);
    }

    @Override
    public void addFirstStepCallback(AddGoodsFirstStepResultBean bean) {
        Intent intent = new Intent(this, GoodsSpecListActivity.class);
        intent.putExtra("goods_id", bean.getGoods_id());
        startActivity(intent);
        finish();
    }

    @Override
    public void getCategoryCallback(AddGoodsAllCategoryBean bean) {
        secondSystemCategoryBeanList = bean.getSys();
        sellerAddCategoryBeanList = bean.getSelf();

        systemSecondCategoryTagAdapter.getDataList().addAll(secondSystemCategoryBeanList);
        systemSecondCategoryTagAdapter.notifyDataChanged();

        sellerAddCategoryTagAdapter.getDataList().addAll(sellerAddCategoryBeanList);
        sellerAddCategoryTagAdapter.notifyDataChanged();
        if (goodsInfoBean != null) {
            String[] ids = goodsInfoBean.getCategory_ids().split(",");
            for (String s : ids) {
                selectedSysCatIds.add(Integer.valueOf(s));
            }

            Set<Integer> selectedSysCatPosition = new HashSet<>();//选中的系统分类 在adapter中的位置
            sysCategoryTv.setText("");//先清空 后面直接append
            for (int i = 0; i < selectedSysCatIds.size(); i++) {
                int id = selectedSysCatIds.get(i);
                for (int j = 0; j < bean.getSelf().size(); j++) {//自己填的分类
                    if (id == bean.getSelf().get(j).getId()) {
                        sellerAddCategoryTagAdapter.setSelectedList(j);
                        sellerCategoryTv.setText(bean.getSelf().get(j).getName());
                    }
                }
                for (int k = 0; k < bean.getSys().size(); k++) {//系统分类
                    if (id == bean.getSys().get(k).getId()) {
                        selectedSysCatPosition.add(k);
                        sysCategoryTv.append(bean.getSys().get(k).getName() + ",");
                    }
                }
            }
            sysCategoryTv.setText(sysCategoryTv.getText().toString().trim().substring(0, sysCategoryTv.getText().toString().trim().length() - 1));//去掉最后的,
            systemSecondCategoryTagAdapter.setSelectedList(selectedSysCatPosition);//setSelectedList这个方法只能放在最外面


        }
    }

    @Override
    public void updateGoodsCallback(String msg) {
        showMessage(msg);
        RxBus.getIntanceBus().post(new RxBusBean(6654));//通知预览页面刷新数据
        finish();
    }

}
